<template>
  <div class="teamConfig">
    <h2 class="title">团队配置</h2>
    <div class="teamConfigBtn">
      <Button type="primary" @click="add">添加配置</Button>
      <Select
        v-model="personSerchVal"
        filterable
        placeholder="请输入员工姓名/工号/手机号搜索"
        style="width: auto; min-width: 300px"
        :remote-method="reFuzzyQuery"
        :loading="loading2"
      >
        <Option v-for="(item, index) in fuzzyList"
          :key="index"
          @click.native="tiao(item)"
          :value="item.userName"
          :label="item.phone + '/' + item.workNo"
        >
          <span>{{ item.userName }}({{ item.workNo }})</span>
          <span>{{ item.buildingName }}</span>
        </Option>
      </Select>
    </div>
    <div class="tab">
      <Table
        ref="TableHeight"
        :max-height="onresizeHeight"
        :columns="columns1"
        :data="dataList"
      ></Table>
    </div>

    <!-- 分页 -->
    <div class="pagePublicStyle" v-show="pageData.total > 0">
      <div class="totalCount">
        当前第 {{ pageData.current }} 页， 当前第
        {{ (pageData.current - 1) * pageData.rows + 1 }} 条到第
        {{
          pageData.current * pageData.rows > pageData.total
            ? pageData.total
            : pageData.current * pageData.rows
        }}
        条， 共 {{ pageData.total }} 条
      </div>
      <Page
        :total="pageData.total"
        :current="pageData.current"
        :page-size-opts="pageData.pageSizeOpts"
        @on-change="pageOnChangeFun"
        @on-page-size-change="pageOnPageSizeChangeFun"
        show-elevator
        show-sizer
        show-total
      />
    </div>
    <!-- 添加配置弹出框 -->
    <Modal v-model="modal" title="添加配置" class="addModel" width="700" @on-cancel='modalCancel'>
      <div class="dui">
        <span>选择楼盘：</span>
        <div class="duiSel">
          <!-- <Select
            v-model="selCityVal"
            :label-in-value="true"
            filterable
            clearable
            placeholder="请选择城市"
            :remote-method="remoteMethod1"
            :loading="loading1"
            @on-change="cityChoose"
            @on-query-change="yunSel"
          > -->
          <Select v-model="selCityVal"  :label-in-value="true" filterable clearable placeholder="请选择城市"
            :remote-method="remoteMethod1" :loading="loading1" @on-change="cityChoose" @on-clear="cityClear" >
            <Option v-for="item in cityList" :value="item.cityCode" :key="item.cityCode" >{{ item.cityName }}</Option >
          </Select>
          <Select v-model="selBuildingVal" clearable filterable :label-in-value="true" @on-change="houseChoose" placeholder="请选择楼盘" >
            <Option v-for="item in cityHouseList" :value="item.buildingId" :key="item.buildingId" >{{ item.buildingAlias }}</Option>
          </Select>
        </div>
      </div>

      <div class="dui" v-for="(item,index) in roleList" :key='index'>
        <span>选择人员：</span>
        <div class="duiSel" >
           <Select v-model="item.roleName"  filterable :multiple="false" clearable placeholder="请选择角色"  @on-open-change="selectedOpen" >
            <Option  v-for="role in roles" :value="role.roleName" :key="role.roleId" >{{ role.roleName }}</Option>
          </Select>
          <Select v-model="item.userName"  filterable :multiple="checkoutName(item.roleName)" clearable placeholder="请选择人员"  @on-open-change="yunSel(index)" >
            <Option  v-for="user in item.yunList" :value="user.userId" :key="user.userId" >{{ user.userName }}</Option>
          </Select>
         <Icon size="20"  class="IconAdd" @click="addRolesForSelected" color="#2d8cf0" type="md-add-circle" />
         <Icon size="20" v-if="index !== 0" @click="roleList.splice(index,1)" class="IconAdd" color="red" type="md-close-circle" />
        </div>
      </div>
      <!-- <div class="dui">
        <span>线上顾问：</span>
        <div class="duiSel">
          <Select
            v-model="adviserVal"
            filterable
            :multiple="true"
            placeholder="请选择人员"
            @on-query-change="remoteSel"
            @on-open-change="guSel"
          >
            <Option
              v-for="item in guList"
              :value="item.userId"
              :key="item.userId"
              >{{ item.userName }}</Option
            >
          </Select>
        </div>
      </div>
      <div class="dui">
        <span>店长：</span>
        <div class="duiSel">
          <Select
            v-model="shopownerVal"
            filterable
            :multiple="false"
            clearable
            placeholder="请选择人员"
            @on-query-change="remoteSel"
            @on-open-change="dianSel"
          >
            <Option
              v-for="item in dianList"
              :value="item.userId"
              :key="item.userId"
              >{{ item.userName }}</Option
            >
          </Select>
        </div>
      </div> -->
      <!-- <div class="dui">
        <span>副店长：</span>
        <div class="duiSel">
          <Select
            v-model="fuShopownerVal"
            filterable
            :multiple="false"
            clearable
            placeholder="请选择人员"
            @on-query-change="remoteSel"
            @on-open-change="fuDianSel"
          >
            <Option
              v-for="item in fuDianList"
              :value="item.userId"
              :key="item.userId"
              >{{ item.userName }}</Option
            >
          </Select>
        </div>
      </div> -->

      <div slot="footer">
        <Button type="text" size="large" @click="modalCancel">取消</Button>
        <Button type="primary" size="large" @click="modalOk">确定</Button>
      </div>
    </Modal>
  </div>
</template>
<script>

import { Message } from "view-design";
import {
  getUserBuilding,
  getCityList,
  getCityHouseList,
  getUserList,
  getHouseTeamCreate,
  getFuzzyQuery,
  getUserListForUserId
} from "@/api/configure.js";
 import { getRoleList} from '@/api/system_center'
 import {getByAdviser} from "@/api/materialManagement"
export default {
  components: {},
  data() {
    return {
      userMess: JSON.parse(this.$tool.getStorage("userMess")),
      personSerchVal: "", //搜索
      fuzzyList: [],

      loading1: false,
      loading2: false,
      cityList: [],
      cityHouseList: [],
      yunList: [],
      guList: [],
      dianList: [],
      fuDianList: [],

      searchUser: "",
      searchCityName: "",

      onresizeHeight: 0, //tabl高
      modal: false,

      // 添加弹框
      selCityVal: "", //城市
      selBuildingVal: "", //楼盘

      selCityChooseVal: "",
      selBuildingChooseVal: "",

      operateVal: "",
      adviserVal: "",
      shopownerVal: "",
      fuShopownerVal: "",

      roleList:[
        {userName:"",roleName:''}
      ],
      roles:[],
      //分页
      pageData: {
        total: 0,
        current: 1,
        rows: 10,
        pageSizeOpts: [10, 20, 30, 40, 50],
      },
      currentRole:'',
      //分页
      cityPageData: {
        total: 0,
        current: 1,
        rows: 50,
        pageSizeOpts: [10, 20, 30, 40, 50],
      },

      columns1: [
        {
          title: "楼盘名称",
          key: "buildingAlias",
          minWidth: 120,
          className: "firstColumns",
          render: (h, params) => {
            return h("div", [
              h(
                "span",
                {
                  style: {
                    display: "inline-block",
                    width: "100%",
                    overflow: "hidden",
                    textOverflow: "ellipsis",
                    whiteSpace: "nowrap",
                  },
                  domProps: {
                    title: params.row.buildingAlias,
                  },
                },
                params.row.buildingAlias
              ),
            ]);
          },
        },
        {
          title: "所属城市",
          key: "cityName",
          minWidth: 120,
        },
        {
          title: "区县-板块",
          key: "areaName",
          minWidth: 120,
          render(h, params) {
            return h("div", `${params.row.areaName}-${params.row.streetName}`);
          },
        },
        {
          title: "操作",
          key: "operation",
          width: 120,
          align: "center",
          render: (h, params) => {
            return h("div", [
              h(
                "a",
                {
                  on: {
                    click: (e) => {
                      e.stopPropagation();
                      this.goTeamList(params.row); //点击事件
                    },
                  },
                },
                "查看团队"
              ),
            ]);
          },
        },
      ],

      dataList: [],
    };
  },
  methods: {
    //添加选择人员列表
    addRolesForSelected(){
       let flag = this.roleList.some(item=>!item.userName || !item.roleName);
       console.log(6666,flag)
       if(flag)return this.$Message.error("请填写完成再添加");
       this.roleList.push({userName:"",roleName:''});
    },
    tiao(val) {
      console.log(val, "tiao");
      this.$router.push({
        path: "/configure_center/teamConfig/teamList",
        query: {
          buildingId: val.buildingId,
          teamId: val.teamId,
          buildingAlias: val.buildingName,
        },
      });
    },
    //模糊查询
    reFuzzyQuery(val) {
      this.loading2 = true;
      console.log(val, "valval");
      if (val != "") {
        let params = {
          searchKey: val,
        };
        getFuzzyQuery(params)
          .then((res) => {
            this.loading2 = false;
            console.log("模糊查询列表", res);

            this.fuzzyList = res.list;

            console.log("模糊查询列表1", this.fuzzyList);
          })
          .catch((err) => {
            this.$Message.error(err);
          });
      }
    },

    cityChoose(val) {
      this.selCityChooseVal = val;
      console.log(this.selCityVal, val, "我选择了城市");
      this.reCityHouseList();
      // this.remoteMethod1();
    },
    houseChoose(val) {
      this.selBuildingChooseVal = val;
      console.log(this.selBuildingChooseVal, "this.selBuildingChooseVal");
    },
    //城市模糊搜索
    remoteMethod1(val) {
      console.log(val, this.selCityVal, "我是远程搜索");
      this.loading1 = true;
      this.searchCityName = val;
      this.reCityList();
    },
    cityClear() {
      this.searchCityName = "";
      this.reCityList();
    },
    modalOk() {
      if (this.selCityVal == "") return this.$Message.warning("请选择城市");
      if (this.selBuildingVal == "") return this.$Message.warning("请选择楼盘");
      let flag,flag1,roleNames=[],appId = this.$tool.getStorage("appId");
      this.roleList.map(item=>{
          if(!item.userName || !item.roleName)flag = true;
          flag1 = roleNames.indexOf(item.roleName)>-1;
          roleNames.push(item.roleName);
      })
      if(flag)return this.$Message.error("请完善人员选择");
      if(flag1)return this.$Message.error("选择角色不能重复，请修改");
      if((appId == 36 && roleNames.indexOf('顾问')<0) || (appId == 49 && roleNames.indexOf('线上顾问')<0))return this.$Message.error(`创建团队配置，${appId == 36?'顾问':appId == 49?'线上顾问':''}角色必选`);
      this.reHouseTeamCreate();
    },
    modalCancel() {
      this.modal = false;
      this.selCityVal = "",
      this.selBuildingVal = "",
      this.selBuildingChooseVal ="";
      this.selCityChooseVal = "";
      this.fuShopownerVal = "";
      this.adviserVal = "";
      this.operateVal = "";
      this.shopownerVal = "";

      console.log('quxiao')
    },
    //创建楼盘团队
    reHouseTeamCreate() {
      let operationalPlanning,onLineAdviser=[],adviser=[],shopManager,appId=this.$tool.getStorage("appId");
      //创建的时候  要分DT跟B+  B+  店长和运营策划角色可以存在多个案场 别的角色只能存在一个案场   D+所有角色都能存在多个案场
      this.roleList.map(item => {
        if(appId == 36){
           Array.isArray(item.userName)
           ?adviser = adviser.concat(item.userName)
           :adviser.push(item.userName)
        }
        else if(appId == 49){
         if(item.roleName === '店长')shopManager = item.userName;
         else if(item.roleName === '运营策划')operationalPlanning = item.userName;
         else{
           if(Array.isArray(item.userName)){
              onLineAdviser = onLineAdviser.concat(item.userName)
           }else{
             onLineAdviser.push(item.userName)
           }
         }
        }
        
      })
      let params = {
        buildingId: this.selBuildingChooseVal.value,
        buildingName: this.selBuildingChooseVal.label,
        cityCode: this.selCityChooseVal.value,
        cityName: this.selCityChooseVal.label,
        cooperationState: 2, //合作状态
        createrId: this.userMess.userId, //创建人
        operationalPlanning, //运营策划
        shopManager, //店长
        adviser,//顾问
        ifInitStandingBook:1,//初始化本案台账
        ifInitHead:1 //初始化客户列表头字段
      };
      if(appId == 49){
         params.onLineAdviser = onLineAdviser;
      }
      getHouseTeamCreate(params)
        .then((res) => {
          this.$Message.success("添加成功")
          this.modalCancel();
          this.reUserBuilding();
        })
        .catch((err) => {
          this.$Message.error(err);
          console.log("错了", err);
        });
    },

    //楼盘团队列表
    reUserBuilding() {
      let params = {
        userId: this.userMess.userId,
        page:this.pageData.current,
        rows:this.pageData.rows
      };
      getUserBuilding(params)
        .then((res) => {
          console.log("楼盘团队列表", res);
          if (res) {
            this.dataList = res.list;
            this.pageData.total = parseInt(res.total);
          }
        })
        .catch((err) => {
          this.$Message.error(err);
          console.log("错了", err);
        });
    },
   //判断是否多选
   checkoutName(name){
      return name !== '运营策划' &&  name !== '店长'
   },
    //城市列表
    reCityList() {
      let params = {
        userId: this.userMess.userId,
        level: 3,
        cityName: this.searchCityName,
        page: this.cityPageData.current,
        rows: this.cityPageData.rows,
      };
      getCityList(params)
        .then((res) => {
          this.loading1 = false;
          console.log("城市", res);
          this.cityList = res.list;
        })
        .catch((err) => {
          console.log("错了", err);
        });
    },

    yunSel(val) {
        this.reUserList(val);
    },
    remoteSel(name,val) {
      console.log(val, "搜索");
      this.searchUser = val;
      this.reUserList(name);
    },

    //用户列表
    reUserList(index) {
      let mess = this.roleList[index],{roleName} = mess,
      roleId = this.rolesAll.find(item=>item.roleName == roleName).roleId,
      params = {
        roleId,
        searchKey: this.searchUser,
      };
      getByAdviser(params)
        .then((res) => {
          console.log("人员列表",res,index);
           mess.yunList = this.$tool.deepClone(res.list);
          this.roleList.splice(index,1,mess);
          console.log(this.roleList)
        })
        .catch((err) => {
          console.log("错了", err);
        });
    },
    //角色列表
    getRoles(roleName=''){
      getRoleList({roleName, page:1,rows:50}).then(res=>{
        console.log("角色列表",res)
        if(!roleName)this.rolesAll = this.$tool.deepClone(res.list);
         this.roles = res.list;
      })
    },
    //点击角色筛选人员
    selectedOpen(){
      this.roles = this.$tool.deepClone(this.rolesAll)
    },
    //根据城市楼盘列表
    reCityHouseList() {
      let params = {
        cityCode: this.selCityVal,
        page: 1,
        rows: 100,
        buildingStatus: 1,
      };
      // getNewBuildingInfoList(params)
      getCityHouseList(params)
        .then((res) => {
          console.log("根据城市楼盘列表", res);
          if (res) {
            this.cityHouseList = res.list;
          }
        })
        .catch((err) => {
          console.log("错了", err);
        });
    },

    add() {
      this.modal = true;
      this.roleList =[{userName:"",roleName:''}],
      this.reCityList(); //城市列表
      this.getRoles(); //用户列表
    },
    goTeamList(val) {
      console.log(val, "111111111111");
      this.$router.push({
        path: "/configure_center/teamConfig/teamList",
        query: {
          buildingId: val.buildingId,
          teamId: val.teamId,
          buildingAlias: val.buildingAlias,
          cityName:val.cityName
        },
      });
    },

    // 分页 页码改变事件
    pageOnChangeFun(page) {
      this.pageData.current = page;
      this.reUserBuilding();
    },
    // 分页 每页条数改变事件
    pageOnPageSizeChangeFun(page) {
      this.pageData.rows = page;
      this.reUserBuilding();
    },
    // 初始化获取数据
    initData() {
      this.$nextTick(() => {
        this.onresizeHeight =
          window.innerHeight - this.$refs.TableHeight.$el.offsetTop - 100;
      });
    },
  },
  computed: {},
  created() {
    this.initData();
    this.reUserBuilding();
    console.log(JSON.parse(this.$tool.getStorage("userMess")), "登录信息");
  },
  activated() {},
  deactivated() {},
  mounted() {
    window.onresize = () => {
      return (() => {
        setTimeout(() => {
          this.onresizeHeight =
            window.innerHeight - this.$refs.TableHeight.$el.offsetTop - 150;
        }, 10);
      })();
    };
  },
  watch: {
    // "$route"(to, from) {
    //   if(to.path == "######") {
    //     this.initData();
    //   }
    // }
  },
};
</script>
<style lang="scss" scoped>
.teamConfig {
  .title {
    padding: 8px 14px;
  }
  .allCustomersP {
    padding: 8px 14px;
  }
  .teamConfigBtn {
    margin: 10px 0;
    padding-left: 14px;
    display: flex;
    flex-direction: row;
    button {
      margin-right: 10px;
    }
    /deep/.ivu-select-item {
      display: flex;
      flex-direction: row;
      justify-content: space-between;
    }
  }
  .tab {
    margin: 10px 0;
  }
  .firstColumns {
    padding-left: 20px;
  }
  
}
.modalCon {
  display: flex;
  flex-direction: row;
  margin-top: 20px;
}
.IconAdd{
  float: right;
  margin: 6px;   
}
.totalCount{
  float: left;
  margin-left: 8px;
}
.dui {
  display: flex;
  flex-direction: row;
  margin-top: 10px;
  & > span {
    flex: 2;
    text-align: right;
    line-height: 30px;
  }
  .duiSel {
    display: flex;
    flex-direction: row;
    flex: 9;
  }
}
/* page */
.pagePublicStyle {
  text-align: right;
  padding: 14px 0;
  margin-right: 30px;
}
.addModel{
 /deep/.ivu-select.ivu-select-single,.ivu-select-multiple{
  width: 230px;
 }
}

</style>
